// pages/madeph/madeph.js
const app = getApp();

//js的这部分有很多是找的轮子，谢谢分享轮子的网友
/**
 * 大概两部分：
 * 1、先把用户上传的头像画出来，类一个圆
 * 2、把前一个页面传过来的头像框（中间透明）在画上去就基本结束了
 * PS：思路比较清晰，但细节完善的不是很好，只能说能用吧。
 */
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: '../../images/dangao.png',
    bgsrc: '',
    bgcss: '',
    canGenerate: false,
    newph: true,
    ifshow:false
  },
  //选择用户自己头像图片
  upload() {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //将选择的图传至upload页处理
        wx.navigateTo({
          url: `../upload/upload?src=${src}`
        })
      }
    })
  },

  refreshAvator_true() {
    console.log("In refreshAvator_true:")
    console.log(this.data.src)
    let self_true = this;
    console.log("self_true.data.src:")
    console.log(self_true.data.src)
    console.log(self_true.data.bgsrc)
    let contex_true = wx.createCanvasContext('ahaucanvas_true',this); //ttcanvas为该canvas的ID
    contex_true.save();
    contex_true.drawImage(self_true.data.src, 0, 0, 1000, 1000);
    contex_true.restore();
    contex_true.save();
    contex_true.drawImage(self_true.data.bgsrc, 0, 0, 1000, 1000); 
    contex_true.restore();
    let outerThis_true = this;
    contex_true.draw(true, function() {
      outerThis_true.setData({
        canGenerate: true
      })
    });
  },

  //生成头像，即先画图像再画图像框
  refreshAvator() {
    let self = this;
    let contex = wx.createCanvasContext('ahaucanvas',this); //ttcanvas为该canvas的ID
    console.log("In refreshAvator:")
    console.log(this.data.src)
    contex.save();
    // contex.drawImage(self.data.src, 0, 0, 2000, 2000);
    this.setData({
      src:self.data.src
    })
    contex.restore();
    contex.save();
    contex.drawImage(self.data.bgsrc, 0, 0, 120, 120); // 这个是我的背
    contex.restore();
    let outerThis = this;
    contex.draw(true, function() {
      outerThis.setData({
        canGenerate: true
      })
    });
  },

  generate() {
      console.log("Generate")
      wx.canvasToTempFilePath({ //导出图片
        width: 1000,
        height: 1000,
        destWidth:1000,
        destHeight: 1000,
        canvasId: 'ahaucanvas_true',
        success: res => {
          console.log("res.tempFilePath")
          console.log(res.tempFilePath);
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              // console.log(data);
              console.log("Save succeed")
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
            },
            fail: function (err) {
              // console.log(err);
              console.log("save Fail")
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                // console.log("用户一开始拒绝了，我想再次发起授权")
                // console.log('打开设置窗口')
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      // console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      wx.showToast({
                        title: '请再次保存',
                        icon: 'success',
                        duration: 2000
                      })
                    } else {
                      // console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      wx.showToast({
                        title: '获取权限失败，可能导致保存图片无法正常使用',
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }
                })
              }
            }
          })
        },
        fail:res=>{
          console.log("canvasToTempFile fail")
        }
      }, this)
  },

  onLoad(option) {
    var that = this;
    var bgcss = app.globalData.toubgsrc.substr(14, 2);
    that.setData({
      bgsrc: app.globalData.toubgsrc,
      bgcss: bgcss,
      // newph = false
    });
    console.log(option)
    console.log(typeof(option))
    let {
      avatar, hasUserInfo
    } = option;
    console.log("Param")
    console.log(avatar)
    console.log(hasUserInfo)
    if(hasUserInfo == 'true')
      hasUserInfo = true
    if (avatar == undefined) {
      avatar = "../../images/dangao.png";
    }
    if(hasUserInfo == true)
    {
      console.log("Has info")
      wx.downloadFile({
        url: avatar,
        success: function (res) {
          console.log("Succeed downloading")
          avatar = res.tempFilePath
          console.log(avatar)
          that.setData({
            src: avatar,
          });
          that.refreshAvator();
          that.refreshAvator_true();
        }
     })
   }
   else{
    this.setData({
      src: avatar,
    });
     this.refreshAvator();
     this.refreshAvator_true();
   }
  }
})